

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="风间">
  <meta name="keywords" content="">
  
    <meta name="description" content="1. Spring IoC 依赖查找   内容    依赖查找的今世前生   单一类型依赖查找   集合类型依赖查找   层次性依赖查找   延迟依赖查找   安全依赖查找   内建可查找的依赖   依赖查找中的经典异常   面试题精选   2. 依赖查找的前世今生 单一类型依赖查找   JNDI - javax.naming.Context#lookup(javax.naming.Name)">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring 核心编程思想（五）：Spring 依赖查找">
<meta property="og:url" content="http://example.com/2023/05/18/%E5%90%8E%E7%AB%AF/java/spring%E6%A0%B8%E5%BF%83%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3%EF%BC%88%E4%BA%94%EF%BC%89/index.html">
<meta property="og:site_name" content="风间小栈">
<meta property="og:description" content="1. Spring IoC 依赖查找   内容    依赖查找的今世前生   单一类型依赖查找   集合类型依赖查找   层次性依赖查找   延迟依赖查找   安全依赖查找   内建可查找的依赖   依赖查找中的经典异常   面试题精选   2. 依赖查找的前世今生 单一类型依赖查找   JNDI - javax.naming.Context#lookup(javax.naming.Name)">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://s3.bmp.ovh/imgs/2023/05/19/b5298159ed069919.jpg">
<meta property="article:published_time" content="2023-05-18T08:51:38.195Z">
<meta property="article:modified_time" content="2023-05-19T07:24:39.746Z">
<meta property="article:author" content="风间">
<meta property="article:tag" content="spring">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://s3.bmp.ovh/imgs/2023/05/19/b5298159ed069919.jpg">
  
  
  <title>Spring 核心编程思想（五）：Spring 依赖查找 - 风间小栈</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.8.13","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":"§"},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>风间小栈</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/img/%E6%96%87%E6%9C%AC.jpg') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="Spring 核心编程思想（五）：Spring 依赖查找">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2023-05-18 16:51" pubdate>
        2023年5月18日 下午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      6.9k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      58 分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Spring 核心编程思想（五）：Spring 依赖查找</h1>
            
            <div class="markdown-body">
              <h2 id="1-Spring-IoC-依赖查找"><a href="#1-Spring-IoC-依赖查找" class="headerlink" title="1. Spring IoC 依赖查找"></a>1. Spring IoC 依赖查找</h2><table>
<thead>
<tr>
<th>内容</th>
</tr>
</thead>
<tbody><tr>
<td>依赖查找的今世前生</td>
</tr>
<tr>
<td>单一类型依赖查找</td>
</tr>
<tr>
<td>集合类型依赖查找</td>
</tr>
<tr>
<td>层次性依赖查找</td>
</tr>
<tr>
<td>延迟依赖查找</td>
</tr>
<tr>
<td>安全依赖查找</td>
</tr>
<tr>
<td>内建可查找的依赖</td>
</tr>
<tr>
<td>依赖查找中的经典异常</td>
</tr>
<tr>
<td>面试题精选</td>
</tr>
</tbody></table>
<h2 id="2-依赖查找的前世今生"><a href="#2-依赖查找的前世今生" class="headerlink" title="2. 依赖查找的前世今生"></a>2. 依赖查找的前世今生</h2><ol>
<li>单一类型依赖查找</li>
</ol>
<ul>
<li><p>JNDI - javax.naming.Context#lookup(javax.naming.Name)</p>
</li>
<li><p>JavaBeans - java.beans.beancontext.BeanContext</p>
</li>
</ul>
<ol start="2">
<li>集合类型依赖查找</li>
</ol>
<ul>
<li>java.beans.beancontext.BeanContext</li>
</ul>
<ol start="3">
<li>层次性依赖查找</li>
</ol>
<ul>
<li>java.beans.beancontext.BeanContext</li>
</ul>
<p>It is desirable to both provide a logical, traversable, hierarchyof JavaBeans, and further to provide a general mechanism whereby an object instantiating an arbitrary JavaBean can offer that JavaBean a variety of services, or interpose itself between the uniderlying system service and the JavaBean, in a conventional fashion.</p>
<p>这段文字主要讲述了在Java编程中，提供一个有逻辑和可遍历的 JavaBean 层次结构的需求，同时还需要提供一种通用机制，使得实例化JavaBean对象的对象可以向其提供各种服务或者在系统服务和JavaBean之间插入自己。通俗的说，就是需要建立一个 JavaBean 的层次结构，并提供一种机制，以便在 JavaBean 使用过程中可以提供服务。</p>
<p>具体来说，要实现这个需求，需要考虑以下几个方面：</p>
<ol>
<li><p>JavaBean 的层次结构：可以使用组合模式来实现JavaBean的逻辑、可遍历的层次结构，以便可以按照树形结构来查找和访问JavaBean。</p>
</li>
<li><p>服务提供机制：可以使用反射机制和注入等技术来实现服务提供机制，使得可以在JavaBean实例化时向其注入服务对象，并在需要时调用服务对象的方法来为JavaBean提供服务。</p>
</li>
<li><p>中介模式：可以使用代理或装饰器等模式来实现中介模式，使得JavaBean可以通过中介对象来访问系统服务或者其他JavaBean。通过中介对象，可以在系统服务和JavaBean之间添加额外的逻辑处理。</p>
</li>
</ol>
<p>综上所述，建立一个 JavaBean 的层次结构并提供服务机制是Java编程中常见的需求，可以通过组合模式、反射机制、注入、代理或装饰器等技术来实现。</p>
<p><img src="https://s3.bmp.ovh/imgs/2023/05/19/7f7b7f4337b8091c.png" srcset="/img/loading.gif" lazyload alt="javabeans"></p>
<h2 id="3-单一依赖查找"><a href="#3-单一依赖查找" class="headerlink" title="3. 单一依赖查找"></a>3. 单一依赖查找</h2><p>单一类型依赖查找接口-BeanFactory</p>
<ol>
<li>根据 Bean 名称查找</li>
</ol>
<ul>
<li><p>getBean(String)</p>
</li>
<li><p>Spring 2.5 覆盖默认参数:getBean(String,Object…)</p>
</li>
</ul>
<ol start="2">
<li>根据 Bean 类型查找</li>
</ol>
<ul>
<li><p>Bean 实时查找</p>
<ul>
<li><p>Spring 3.0 getBean(Class)</p>
</li>
<li><p>Spring 4.1 覆盖默认参数:getBean(Class,Object…)</p>
</li>
</ul>
</li>
</ul>
<p>**tips:**关于覆盖参数这个方法的调用，建议大家不需要去掌握，也不需要去运用，因为这个非常危险。因为这个接口会覆盖掉默认的一些参数，同时我们会看到 API 里面有这么一个描述</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * Return an instance, which may be shared or independent, of the specified bean.</span><br><span class="hljs-comment"> * &lt;p&gt;Allows for specifying explicit constructor arguments / factory method arguments,</span><br><span class="hljs-comment"> * overriding the specified default arguments (if any) in the bean definition.</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@param</span> name the name of the bean to retrieve</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@param</span> args arguments to use when creating a bean instance using explicit arguments</span><br><span class="hljs-comment"> * (only applied when creating a new instance as opposed to retrieving an existing one)</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@return</span> an instance of the bean</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@throws</span> NoSuchBeanDefinitionException if there is no such bean definition</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@throws</span> BeanDefinitionStoreException if arguments have been given but</span><br><span class="hljs-comment"> * the affected bean isn&#x27;t a prototype</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@throws</span> BeansException if the bean could not be created</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@since</span> 2.5</span><br><span class="hljs-comment"> */</span><br><span class="hljs-function">Object <span class="hljs-title">getBean</span><span class="hljs-params">(String name, Object... args)</span> <span class="hljs-keyword">throws</span> BeansException</span>;<br></code></pre></td></tr></table></figure>

<p>实例可能是 shared 可能是 independent，这个 share d就是指的单例，那么 independent 主要是原生。这里就会告诉你一个不好的特点，如果当你是 shared 的话，你每调一次就会覆盖它的方法，这种方式实际上是有点不可取的。</p>
<ul>
<li>Spring 5.1 Bean 延迟查找<ul>
<li>getBeanProvider(Class)</li>
<li>getBeanProvider(ResolvableType)</li>
</ul>
</li>
</ul>
<p>BeanFactory:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java">&lt;T&gt; <span class="hljs-function">ObjectProvider&lt;T&gt; <span class="hljs-title">getBeanProvider</span><span class="hljs-params">(Class&lt;T&gt; requiredType)</span></span>;<br></code></pre></td></tr></table></figure>

<p>ObjectProvider:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">ObjectProvider</span>&lt;<span class="hljs-title">T</span>&gt; <span class="hljs-keyword">extends</span> <span class="hljs-title">ObjectFactory</span>&lt;<span class="hljs-title">T</span>&gt;, <span class="hljs-title">Iterable</span>&lt;<span class="hljs-title">T</span>&gt; </span>&#123;...<br></code></pre></td></tr></table></figure>

<p>OjbectProvider 是继承了 ObjectFactory，ObjectFactory 它就通过某种参数关联类型去关联一个特性</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * &lt;h1&gt;通过&#123;<span class="hljs-doctag">@link</span> org.springframework.beans.factory.ObjectProvider&#125;进行依赖查找&lt;/h1&gt;</span><br><span class="hljs-comment"> *</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@author</span> 风间</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@since</span> 2023/5/19</span><br><span class="hljs-comment"> */</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ObjectProviderDemo</span> </span>&#123;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>        AnnotationConfigApplicationContext applicationContext = <span class="hljs-keyword">new</span> AnnotationConfigApplicationContext();<br>        applicationContext.register(ObjectProviderDemo.class);<br>        applicationContext.refresh();<br><br>        lookupByObjectProvider(applicationContext);<br><br>        applicationContext.close();<br>    &#125;<br><br>    <span class="hljs-meta">@Bean</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">hello</span><span class="hljs-params">()</span> </span>&#123;<span class="hljs-comment">// 方法名就是 Bean 名称 = &quot;hello&quot;</span><br>        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;hello&quot;</span>;<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">lookupByObjectProvider</span><span class="hljs-params">(AnnotationConfigApplicationContext applicationContext)</span> </span>&#123;<br><br>        ObjectProvider&lt;String&gt; beanProvider = applicationContext.getBeanProvider(String.class);<br>        String object = beanProvider.getObject();<br>        System.out.println(object);<br><br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<ol start="3">
<li>根据 Bean 名称 + 类型查找:getBean(String,Class)</li>
</ol>
<h2 id="4-集合类型依赖查找"><a href="#4-集合类型依赖查找" class="headerlink" title="4. 集合类型依赖查找"></a>4. 集合类型依赖查找</h2><p>集合类型依赖查找接口-ListableBeanFactory</p>
<ol>
<li>根据 Bean 类型查找</li>
</ol>
<ul>
<li><p>获取同类型 Bean 名称列表</p>
<ul>
<li>getBeanNamesForType(Class)</li>
<li>Spring 4.2 getBeanNamesForType(ResolvableType)</li>
</ul>
</li>
<li><p>获取同类型 Bean 实例列表</p>
<ul>
<li>getBeansOfType(Class)以及重载方法</li>
</ul>
</li>
</ul>
<ol start="2">
<li>通过注解类型查找</li>
</ol>
<ul>
<li><p>Spring 3.0 获取标注类型 Bean 名称列表</p>
<ul>
<li>getBeanNamesForAnnotation(Class&lt;? extends Annotation&gt;)</li>
</ul>
</li>
<li><p>Spring 3.0 获取标注类型 Bean 实例列表</p>
<ul>
<li>getBeansWithAnnotation(Class&lt;? extends Annotation&gt;)</li>
</ul>
</li>
<li><p>Spring 3.0 获取指定名称+标注类型 Bean 实例</p>
<ul>
<li>findAnnotationOnBean(String,Ciass&lt;? extends Annotation&gt;)</li>
</ul>
</li>
</ul>
<h2 id="5-层次性依赖查找"><a href="#5-层次性依赖查找" class="headerlink" title="5. 层次性依赖查找"></a>5. 层次性依赖查找</h2><p>层次性依赖查找接口-HierarchicalBeanFactory</p>
<ol>
<li><p>双亲 BeanFactory:getParentBeanFactory()</p>
</li>
<li><p>层次性查找</p>
</li>
</ol>
<ul>
<li><p>根据 Bean 名称查找</p>
<ul>
<li>基于 containsLocalBean 方法实现</li>
</ul>
</li>
<li><p>根据Bean类型查找实例列表</p>
<ul>
<li>单一类型:BeanFactoryUtils#beanOfType</li>
<li>集合类型:BeanFactoryUtils#beansOfTypelncludingAncestors</li>
</ul>
</li>
<li><p>根据 Java 注解查找名称列表</p>
<ul>
<li>BeanFactoryUtils#beanNamesForTypelncludingAncestors</li>
</ul>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br><br>    <span class="hljs-comment">// 创建  容器</span><br>    AnnotationConfigApplicationContext applicationContext = <span class="hljs-keyword">new</span> AnnotationConfigApplicationContext();<br>    <span class="hljs-comment">// 将当前类 AnnotationApplicationContextAsIoCContainerDemo 作为配置类（Configuration Class）</span><br>    applicationContext.register(AnnotationApplicationContextAsIoCContainerDemo.class);<br>    <span class="hljs-comment">// 启动应用上下文</span><br>    applicationContext.refresh();<br><br>    <span class="hljs-comment">// 1. 获取 HierarchicalBeanFactory &lt;- ConfigurableBeanFactory &lt;- ConfigurableListableBeanFactory</span><br>    ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory();<br>    System.out.println(<span class="hljs-string">&quot;获取 BeanFactory 的 Parent BeanFactory : &quot;</span> + beanFactory.getParentBeanFactory());<br>    <span class="hljs-comment">// 2. 设置 Parent BeanFactory</span><br>    HierarchicalBeanFactory parentBeanFactory = crateParentBeanFactory();<br>    beanFactory.setParentBeanFactory(parentBeanFactory);<br>    System.out.println(<span class="hljs-string">&quot;获取 BeanFactory 的 Parent BeanFactory : &quot;</span> + beanFactory.getParentBeanFactory());<br><br>    displayLocalBean(beanFactory,<span class="hljs-string">&quot;user&quot;</span>);<br>    displayLocalBean(parentBeanFactory,<span class="hljs-string">&quot;user&quot;</span>);<br><br>    displayContainsBean(beanFactory,<span class="hljs-string">&quot;user&quot;</span>);<br>    displayContainsBean(parentBeanFactory,<span class="hljs-string">&quot;user&quot;</span>);<br>    <span class="hljs-comment">// 关闭应用上下文</span><br>    applicationContext.close();<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">displayContainsBean</span><span class="hljs-params">(HierarchicalBeanFactory beanFactory,String beanName)</span></span>&#123;<br><br>    System.out.printf(<span class="hljs-string">&quot;当前 BeanFactory[%s] 是否包含 bean[name : %s]: %s\n&quot;</span>, beanFactory, beanName,<br>            containsBean(beanFactory,beanName));<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">containsBean</span><span class="hljs-params">(HierarchicalBeanFactory beanFactory,String beanName)</span></span>&#123;<br>    BeanFactory parentBeanFactory = beanFactory.getParentBeanFactory();<br>    <span class="hljs-keyword">if</span> (parentBeanFactory <span class="hljs-keyword">instanceof</span> HierarchicalBeanFactory) &#123;<br>        HierarchicalBeanFactory parentHierarchicalBeanFactory = HierarchicalBeanFactory.class.cast(parentBeanFactory);<br>        <span class="hljs-keyword">if</span> (containsBean(parentHierarchicalBeanFactory,beanName)) &#123;<br>            <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;<br>        &#125;<br>    &#125;<br>    <span class="hljs-keyword">return</span> beanFactory.containsLocalBean(beanName);<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">displayLocalBean</span><span class="hljs-params">(HierarchicalBeanFactory beanFactory, String beanName)</span> </span>&#123;<br><br>    System.out.printf(<span class="hljs-string">&quot;当前 BeanFactory[%s] 是否包含 bean[name : %s]: %s\n&quot;</span>, beanFactory, beanName,<br>            beanFactory.containsLocalBean(beanName));<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> ConfigurableListableBeanFactory <span class="hljs-title">crateParentBeanFactory</span><span class="hljs-params">()</span> </span>&#123;<br>    <span class="hljs-comment">// 创建 BeanFactory 容器</span><br>    DefaultListableBeanFactory beanFactory = <span class="hljs-keyword">new</span> DefaultListableBeanFactory();<br>    XmlBeanDefinitionReader reader = <span class="hljs-keyword">new</span> XmlBeanDefinitionReader(beanFactory);<br>    <span class="hljs-comment">// XML 配置文件 classpath 路径</span><br>    String location = <span class="hljs-string">&quot;META-INF/dependency-injection-context.xml&quot;</span>;<br>    <span class="hljs-comment">// 加载配置，返回加载到的 Bean 个数</span><br>    reader.loadBeanDefinitions(location);<br>    <span class="hljs-keyword">return</span> beanFactory;<br><br>&#125;<br></code></pre></td></tr></table></figure>

<h2 id="6-延迟依赖查找"><a href="#6-延迟依赖查找" class="headerlink" title="6. 延迟依赖查找"></a>6. 延迟依赖查找</h2><p>Bean延迟依赖查找接口</p>
<ul>
<li><p>org.springframework.beans.factory.ObjectFactory</p>
</li>
<li><p>org.springframework.beans.factory.ObjectProvider</p>
<ul>
<li>Spring5 对 Java8 特性扩展<ul>
<li>函数式接口<ul>
<li>getIfAvailable(Supplier)</li>
<li>ifAvailable(Consumer)</li>
</ul>
</li>
<li>Stream 扩展-stream()</li>
</ul>
</li>
</ul>
</li>
</ul>
<h2 id="12-面试题"><a href="#12-面试题" class="headerlink" title="12. 面试题"></a>12. 面试题</h2><p><strong><font color="green" size="2">沙雕面试题</font></strong>-什么是 Spring IoC 容器？</p>
<p><strong><font color="orange" size="2">996面试题</font></strong>-BeanFactory 和 FactoryBean 的区别？</p>
<p><strong><font color="red" size="2">劝退面试题</font></strong>-Spring IoC 容器启动时做了哪些准备?？</p>
<p><strong>本节完</strong></p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E5%90%8E%E7%AB%AF/">后端</a>
                    
                      <a class="hover-with-bg" href="/categories/%E5%90%8E%E7%AB%AF/spring-%E6%A0%B8%E5%BF%83%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3/">spring 核心编程思想</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/spring/">spring</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2023/05/09/%E5%90%8E%E7%AB%AF/java/spring%E6%A0%B8%E5%BF%83%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3%EF%BC%88%E5%9B%9B%EF%BC%89/">
                        <span class="hidden-mobile">Spring 核心编程思想（四）：Spring Bean 基础</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments" lazyload>
                
                  
                
                
  <div id="SOHUCS" sid='http://example.com/2023/05/18/%E5%90%8E%E7%AB%AF/java/spring%E6%A0%B8%E5%BF%83%E7%BC%96%E7%A8%8B%E6%80%9D%E6%83%B3%EF%BC%88%E4%BA%94%EF%BC%89/'></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#SOHUCS', function() {
      Fluid.utils.createScript("https://changyan.sohu.com/upload/changyan.js", function() {
        window.changyan.api.config({"appid":"cywjv2D9l","appkey":"2bf2f1231299e92b26393ba6fb2ad9d8"})
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
    风间小栈出品
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
